package com.seagox.chat.util;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.SetBucketPolicyArgs;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Component
public class UploadUtils {
    
	@Value("${oss.endpoint}")
    private String endpoint;
	
	@Value("${oss.access-key}")
    private String accessKey;
	
	@Value("${oss.secret-key}")
    private String secretKey;
	
	@Value("${oss.url}")
    private String url;
	
    /**
     * 通过MultipartFile上传
     * 
     * @param bucketName 存储桶
     * @param objectName 文件对象
     * @param file 文件
     */
	public String putObject(String bucketName, MultipartFile file) {
		InputStream inputStream = null;
		try {
			MinioClient minioClient = MinioClient.builder().endpoint(endpoint)
					.credentials(accessKey, secretKey)
					.build();
			boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
			if (!isExist) {
				minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
				JSONObject config = new JSONObject();
				config.put("Version", "2012-10-17");
				JSONArray statements = new JSONArray(); 
					
				JSONObject statement = new JSONObject();
				statement.put("Action", "s3:GetObject");
				statement.put("Effect", "Allow");
				statement.put("Principal", "*");
				statement.put("Resource", "arn:aws:s3:::"
						+ bucketName
						+ "/*");
				statements.add(statement);
				config.put("Statement", statements);
				minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(config.toJSONString()).build());
			}
			
			inputStream = file.getInputStream();
			
			String prefix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
			String fileName = prefix + "_" + System.currentTimeMillis() + "." + suffix;
			Map<String, String> headers = new HashMap<>();
			headers.put("x-amz-acl", "public-read-write");
			Date date = new Date( );
		    SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMM");
		    String yearMonth = sdf.format(date);	
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(yearMonth + "/" + fileName).stream(inputStream, inputStream.available(), -1).contentType(file.getContentType()).headers(headers).build());
            return url  + "/" + bucketName + "/" + yearMonth + "/" + fileName;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
     * 通过流上传
     * 
     * @param bucketName 存储桶
     * @param objectName 文件对象
     * @param inputStream 文件流
     */
	public String putObject(String bucketName, String objectName, InputStream inputStream) {
		try {
			MinioClient minioClient = MinioClient.builder().endpoint(endpoint)
					.credentials(accessKey, secretKey)
					.build();
			boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
			if (!isExist) {
				minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
				JSONObject config = new JSONObject();
				config.put("Version", "2012-10-17");
				JSONArray statements = new JSONArray(); 
					
				JSONObject statement = new JSONObject();
				statement.put("Action", "s3:GetObject");
				statement.put("Effect", "Allow");
				statement.put("Principal", "*");
				statement.put("Resource", "arn:aws:s3:::"
						+ bucketName
						+ "/*");
				statements.add(statement);
				config.put("Statement", statements);
				minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(config.toJSONString()).build());
			}
			Map<String, String> headers = new HashMap<>();
			headers.put("x-amz-acl", "public-read-write");
			minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(inputStream, inputStream.available(), -1).headers(headers).build());
			return url + "/" + bucketName + "/" + objectName;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
